<template>
	<div class="home" ref="homeRef">
		<home-nav-bar></home-nav-bar>

		<div class="banner">
			<img src="@/assets/img/home/banner.webp" alt="" />
		</div>

		<home-search-box :hotSuggests="hotSuggests"></home-search-box>

		<home-categories></home-categories>

		<div class="search-bar" v-if="isShowSearchBar">
			<search-bar></search-bar>
		</div>
		<home-content></home-content>
	</div>
</template>

<script setup>
	import { onUnmounted, ref, onMounted, onActivated, onDeactivated, watch, computed } from 'vue'
	import HomeNavBar from './cpns/home-nav-bar.vue'
	import HomeCategories from './cpns/home-categories.vue'
	import HomeSearchBox from './cpns/home-search-box.vue'
	import HomeContent from './cpns/home-content.vue'
	import { storeToRefs } from 'pinia'
	import hyRequest from '../../services/request'
	import useHomeStore from '@/stores/modules/home.js'
	import useScroll from '@/hooks/useScroll'
	import SearchBar from '@/components/search-bar/search-bar.vue'

	const homeStore = useHomeStore()
	const homeRef = ref(null)
	// 发送网络请求
	homeStore.fetchHotSuggestDate()
	homeStore.fetchCategoriesData()
	const { hotSuggests } = storeToRefs(homeStore)
	homeStore.fetchHouselistData()

	// 方式1(回调函数)
	/* useScroll(() => {
		homeStore.fetchHouselistData()
	}) */

	// 方式2(变量+watch)
	const { isReachBottom, scrollTop } = useScroll(homeRef)
	watch(isReachBottom, (newVal, oldVal) => {
		if (newVal) {
			homeStore.fetchHouselistData().then(() => {
				isReachBottom.value = false
			})
		}
	})

	// 搜索框显示隐藏
	/* const isShowSearchBar = ref(false)
	watch(scrollTop, (newVal, oldVal) => {
		isShowSearchBar.value = newVal > 100
	}) */

	const isShowSearchBar = computed(() => {
		return scrollTop.value >= 350
	})

	// 跳转到home时, 保留原理的位置
	onActivated(() => {
		homeRef.value?.scrollTo({
			top: scrollTop.value,
		})
	})
</script>

<style scoped lang="less">
	// 不要让window滚动, 不让切换页面时, 其他页面的window也会继承上一个页面的滚动
	.home {
		height: 100vh;
		overflow-y: auto;
		box-sizing: border-box;
		padding-bottom: 60px;
		.banner {
			img {
				width: 100%;
			}
		}

		.search-bar {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			height: 45px;
			padding: 16px 16px 10px;
			background-color: #fff;
			z-index: 9;
		}
	}
</style>
